package cn.selfiot.iotman.helper;

import cn.selfiot.iotman.model.mqtt.ProjectModel;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hugo
 * @since 2020/8/13
 */
public class ProjectPersistHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectPersistHelper.class);
    
    private static final String USER_HOME = System.getProperty("user.home");
    private static final String PROJECT_STORE = USER_HOME + File.separator
            + ".iotman/projects.json";
    
    
    public static void init() {
        File file = new File(PROJECT_STORE);
        if (!file.exists()) {
            file.getParentFile().mkdir();
            List<ProjectModel> projects = new ArrayList<>();
            saveProjects(projects);
        }
    }
    
    /**
     * 从文件获取Project列表
     *
     * @return project列表
     */
    public static List<ProjectModel> getProjects() {
        ObjectMapper objectMapper = new ObjectMapper();
        
        File file = new File(PROJECT_STORE);
        List<ProjectModel> projects = new ArrayList<>();
        try (FileInputStream in = new FileInputStream(file)) {
            ArrayList list = objectMapper.readValue(in, ArrayList.class);
            projects = objectMapper.convertValue(list,
                    new TypeReference<List<ProjectModel>>() {
                    });
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        
        return projects;
    }
    
    /**
     * 写Projects到文件
     *
     * @param projects 项目配置列表
     */
    public static synchronized void saveProjects(List<ProjectModel> projects) {
        ObjectMapper objectMapper = new ObjectMapper();
        try (FileOutputStream out = new FileOutputStream(PROJECT_STORE)) {
            objectMapper.writeValue(out, projects);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }
    
    /**
     * 保存项目信息
     *
     * @param project 项目信息
     */
    public static void saveProject(ProjectModel project) {
        List<ProjectModel> projects = getProjects();
        
        List<ProjectModel> pms = projects.stream()
                .filter(p -> !p.getId().equals(project.getId()))
                .collect(Collectors.toList());
        pms.add(project);
        
        saveProjects(pms);
    }
    
    /**
     * 删除项目信息
     *
     * @param project 项目
     */
    public static void remove(ProjectModel project) {
        List<ProjectModel> projects = getProjects();
        
        List<ProjectModel> pms = projects.stream()
                .filter(p -> !p.getId().equals(project.getId()))
                .collect(Collectors.toList());
        saveProjects(pms);
    }
    
    /**
     * 按项目名称搜索
     *
     * @param projects    项目列表
     * @param projectName 名称
     * @return 项目列表
     */
    public static List<ProjectModel> findByName(List<ProjectModel> projects,
                                                String projectName) {
        if (projectName == null
                || projectName.isEmpty() || projectName.isBlank())
            return getProjects();
        
        return projects.stream()
                .filter(p -> p.getProjectName().contains(projectName))
                .collect(Collectors.toList());
    }
}
